<template>
  <main>
    <el-card>
      <div class="pic">
        <img :src="AVA" alt="404" />
        <li>
          <el-upload
            ref="upload"
            action="http://127.0.0.1:3000/api/usersAva/"
            :multiple="false"
            name="avatar"
            accept="image/jpg, image/jpeg, image/png"
            :on-success="onSuccess"
          >
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </li>
      </div>
      <div class="data">
        <el-form
          :model="regForm"
          :rules="regRules"
          ref="regFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="name">
            <el-input v-model="regForm.name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="regForm.email"></el-input>
            <el-button @click="changeThisPass">更改密码</el-button>

          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="changePass">
            <el-input v-model="regForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sub">提交</el-button>
            <el-button type="info" @click="clear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </main>
</template>

<script>
export default {
  created() {
    this.getUserData();
    
  },
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确邮箱"));
    };
    var checkPass = (rule, value, callback) => {
      const regPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,16}$/;
      if (regPass.test(value)) {
        return callback();
      }
      callback(
        new Error(
          "必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 8-16 之间"
        )
      );
    };
    return {
      changePass:false,
      AVA: "",
      regForm: {
        name: "",
        password: "",
        email: "",
      },
      regRules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 4,
            max: 12,
            message: "长度在 4 到 12 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPass, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getUserData() {
      const { data: res } = await this.$http.get(
        `/users/userGetUserData/${window.sessionStorage.getItem("userId")}`
      );
      this.AVA = res.data.avatar;
      this.regForm.name = res.data.username;
      this.regForm.email = res.data.email;
    },
    async onSuccess(res) {
      let name = res.file.filename;
      let url = `http://127.0.0.1:3000/uploads/users/${name}`;
      this.$refs.upload.clearFiles();
      if (res.status == 200) {
        const { data: resa } = await this.$http.post(
          `/users/changeUserAvatar/${window.sessionStorage.getItem("userId")}`,
          {
            avatar: url,
          }
        );
        if (resa.status == 200) {
          this.getUserData();
          this.$store.state.userData.userAvatar = url;
          //window.sessionStorage.setItem("userAvatar", url);
          window.localStorage.setItem("userAvatar", url);
          //console.log(this.$store.state.userData.userAvatar);
        }
      } else {
        this.$message.error("上传失败");
      }
    },
    clear() {
      this.$refs.regFormRef.resetFields();
    },
    async sub() {
        const{data:res} = await this.$http.post(`/users/updata/${window.sessionStorage.getItem("userId")}`,{
            username:this.regForm.name,email:this.regForm.email,password:this.regForm.password
        }
        )
        if(res == "OK" && this.regForm.password == ''){
            this.getUserData();
            return
        }
        if(res == "OK" && this.regForm.password != ''){
            this.$router.push("/userLogin")
            return
        }
    },
    changeThisPass(){
        this.changePass = true;
    }
  },
};
</script>

<style lang="less" scoped>
main {
  height: 100%;
  width: 100%;
}
li {
  list-style: none;
}
.el-card {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}
.pic {
  width: 100%;
  height: 250px;
  display: flex;
  align-items: center;
}
.pic img {
  height: 180px;
  width: 180px;
}
.data{
    width: 60%;
}
</style>
